package db;

import java.sql.Connection;
import java.util.Date;

import org.apache.cayenne.ObjectContext;
import org.apache.cayenne.ObjectId;
import org.apache.cayenne.access.DataContext;
import org.apache.cayenne.configuration.server.ServerRuntime;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class CRUD {
	private ObjectContext context;
	private DataContext dataContext;
	private Connection conn;

	@Before
	public void setUp() throws Exception {
		ServerRuntime runtime = new ServerRuntime("cayenne-diary.xml");
		context = runtime.getContext();
		conn = runtime.getDataDomain().getNode("diary").getDataSource().getConnection();
	}

	@After
	public void tearDown() throws Exception {
		context.rollbackChanges();
		dataContext = (DataContext)context;		
	}
	
	@Test
	public void crudTrainingDay() throws Exception {
		ObjectContext childContext = context.createChildContext();
		Date now = new Date();
		String user = "REICH";
		db.TrainingDay trainingDay = childContext.newObject(TrainingDay.class);
		trainingDay.setChanged(now);
		trainingDay.setChangedBy(user);
		trainingDay.setCreated(now);
		trainingDay.setCreatedBy(user);
		trainingDay.setDay(now);
		trainingDay.setDescription("Test");				
		childContext.commitChangesToParent();		
		
		ObjectId objectId = trainingDay.getObjectId();
		
		TrainingDay newTrainingDay = (TrainingDay)org.apache.cayenne.Cayenne.objectForPK(childContext, objectId);		
		childContext.deleteObjects(newTrainingDay);
		
		context.commitChanges();
	}
}
